package com.ddf.publics.config;

import com.ddf.publics.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Zero on 2020-6-12 9:37
 */

@Component
public class VerifyCodeFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        if(url.equals("/admin/toLogin") && request.getMethod().equalsIgnoreCase("post")){
            //验证码键
            String validkey = request.getParameter("keycode");
            //用户输入的验证码
            String valid =  request.getParameter("valid");
            String username = request.getParameter("username");
            request.getSession().setAttribute("backUser",username);
            Cookie cookie = new Cookie("key", username);
            cookie.setMaxAge(60*60*24*15);
            response.addCookie(cookie);
            //redis存的验证码
            String code = redisUtil.get(validkey).toString();
            if(code==null||!code.equals(valid)){//验证码错误
                //最好使用失败的处理器
                //loginFailureHandler.onAuthenticationFailure(request,response,e);
                request.setAttribute("msg","验证码错误!");
                request.getRequestDispatcher("/admin/toLogin-error").forward(request,response);
                return;
            }
        }
        // 3. 校验通过，就放行
        filterChain.doFilter(request, response);
    }


}
